<?php

// 用户验证中间件
namespace app\middleware;
use think\Request;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Config;
use think\exception\HttpResponseException;
use think\Response;
class Auth
{
    public function handle(Request $request, \Closure $next)
    {
        $key = Config::get('jwt.secret'); // 你的密钥
		//请求头部信息
		$request->header();

		//获取头部 Authorization字段
		$authorizationHeader = $request->header('Authori-zation');
        if(!$authorizationHeader){
            $response = Response::create(['status' => -1, 'msg' => '非法请求'], 'json', 401);
            throw new HttpResponseException($response);
        }
        $array = explode('Bearer ', $authorizationHeader);
        $token = $array[1];
        $verification_data = $this->verification_token_expires($token);
//        dump('code',$verification_data['code']);
//        如果toke未过期
//        dump('code',$verification_data['code']);
        if($verification_data['code'] == 0){
            $request->openid = $verification_data['openid'];
        }else{
            $response = Response::create(['status' => 410000, 'msg' => 'Token 已过期'], 'json', 401);
//            return  fail(null,40001,'身份已过期,请重新登录');
            throw new HttpResponseException($response);
        }
        // 继续执行请求
        return $next($request);
    }

    //        验证token是否过期
    private static function verification_token_expires($token){

        try {
            $key = Config::get('jwt.secret'); // 你的密钥
            $keys = new Key($key, 'HS256');
            // 解码 Token，自动验证签名和过期时间
            $decoded = JWT::decode($token, $keys);

            // Token 有效，继续处理请求
            // $decoded 中包含了 Token 的信息
            // 例如 $decoded->email 获取用户的邮箱信息
            return array(
                "code" => 0,
                "openid" => $decoded->user_id
            );
        } catch (\Exception $e) {
//            dump('$e',$e);
            // Token 无效或已过期
            // 返回错误信息给前端，比如 401 Unauthorized
            return array(
                "code" => -1
            );
        }
    }
}